package com.example.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.mapper.GoodsCategoryMapper;
import com.example.api.service.GoodsCategoryService;
import com.example.api.vo.GoodsCategoryTreeVO;
import com.example.common.Interface.TreeNode;
import com.example.common.po.GoodsCategoryPO;
import com.example.common.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 商品分类
 */
@Service("apiGoodsCategoryServiceImpl")
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategoryPO>
        implements GoodsCategoryService {

    @Autowired
    public GoodsCategoryMapper goodsCategoryMapper;

    @Autowired
    private TreeUtil treeUtil;

    /**
     * 获取树形列表
     *
     * @return
     */
    @Override
    public List<GoodsCategoryTreeVO> getTree() {
        List<GoodsCategoryPO> list = goodsCategoryMapper.selectList(new QueryWrapper<GoodsCategoryPO>()
                .select("cat_id", "pid", "cat_name", "cat_level", "cat_path")
                .lambda()
                .eq(GoodsCategoryPO::getIsShow, true)
                .orderByAsc(GoodsCategoryPO::getSort)
        );
        // 构建树形节点
        List<TreeNode> treeNode = new ArrayList<>();
        Iterator<GoodsCategoryPO> it = list.iterator();
        while (it.hasNext()) {
            TreeNode i = it.next();
            treeNode.add(i);
        }
        //构建扩展属性
        HashMap<String, String> extraAttrList = new HashMap<>();
        extraAttrList.put("catPath", "getCatPath");
        extraAttrList.put("catLevel", "getCatLevel");
        extraAttrList.put("isShow", "getIsShow");
        treeUtil.setIdKey("catId");
        treeUtil.setNameKey("catName");
        treeUtil.setNodeList(treeNode);
        treeUtil.setExtraAttrList(extraAttrList);
        return GoodsCategoryTreeVO.convertToVO(treeUtil.build());
    }
}




